package com.pmcc.core.config.security;

import com.pmcc.cj.entity.CjCustomer;
import com.pmcc.cj.repository.CjCustomerRepository;
import com.pmcc.core.entity.Employee;
import com.pmcc.core.entity.Role;
import com.pmcc.core.repository.EmployeeRepository;
import com.pmcc.core.repository.RoleRepository;
import com.pmcc.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class JwtUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private EmployeeRepository employeeRepository;
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private CjCustomerRepository cjCustomerRepository;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        boolean isTure = false;
        //查询出人员的信息
        Employee employee = employeeRepository.findByUserName(username);
        CjCustomer customer = new CjCustomer();
        if(StringUtil.isNotEmpty(username) && username.endsWith("&*&*&*&*&*&*&*&*&*&*")){
            isTure = true;
            customer = cjCustomerRepository.findByUserName(username);
        }
        if(isTure){
            Role role=roleRepository.findOne(customer.getRoleId());
            return JwtUserFactory.create1(customer,role);
        }else {
            if (employee == null) {
                throw new UsernameNotFoundException(String.format("查找不到该用户 '%s'.", username));
            } else if(employee.getEnabled().equals("1")){
                throw new UsernameNotFoundException(String.format("该用户名已经被注销 '%s'.", username));
            }else if(employee.getDelFlag() ==1){
                throw new UsernameNotFoundException(String.format("该用户名已经被删除 '%s'.", username));
            }else{
                //查询出角色关联的信息
                Role role=roleRepository.findOne(employee.getRoleId());
                return JwtUserFactory.create(employee,role);
            }
        }

    }
}
